const std = @import("std");
const database = @import("../database/db.zig");
const UserModel = @import("../model/user.zig");

/// 通过id获取用户信息
pub fn getUserById(user_id: u32) !?UserModel.User {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\SELECT id, username, nickname FROM user WHERE id = $id
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const row = try stmt.oneAlloc(struct {
        id: u32,
        username: []const u8,
        nickname: []const u8,
    }, allocator, .{}, .{
        .id = user_id,
    });

    if (row) |r| {
        return UserModel.User{
            .id = r.id,
            .username = r.username,
            .password = undefined,
            .nickname = r.nickname,
        };
    }

    return null;
}

/// 通过用户名获取用户信息
pub fn getUserByUsername(username: []const u8) !?UserModel.User {
    var db = try database.OpenDb();
    defer db.deinit();

    const query =
        \\SELECT id, username, password, nickname FROM user WHERE username = $username
    ;

    var stmt = try db.prepare(query);
    defer stmt.deinit();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const row = try stmt.oneAlloc(UserModel.User, allocator, .{}, .{
        .username = username,
    });

    if (row) |r| {
        return r;
    }

    return null;
}
